<?php

/**
 * 微电汇项目 --CRM接口类
 * @author   shujieyang <shujieyang@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Rpc\Crm;

use DB;

use Carbon\Carbon;

use App\Models\Customer\Customer;  //会员主表

use App\Models\Customer\CustAccount;  //客户帐户表

use App\Models\Customer\CustAccountLog;  //客户帐户变更表

class EbsigCrm
{

    /**
     * 查询会员账户积分信息
     * @param $args_array
     * @return array
     */
    public function pointsQuery( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        //查询会员信息
        $customer = Customer::select('pcustID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100002,'message'=>'会员信息不存在'];
        }

        $points = 0;

        //查询账户可用积分
        $cust_account = CustAccount::select('useableAccount')->where(['pcustID'=>$customer['pcustID'],'subjectId'=>3])->first();
        if ( $cust_account ) {
            $points = app_to_int( $cust_account['useableAccount'] );
        }


        return ['code'=>200,'message'=>'ok','data'=>['points' => $points] ];
    }


    /**
     * 查询会员账户余额信息
     * @param $args_array
     * @return array
     */
    public function accountQuery( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        //查询会员信息
        $customer = Customer::select('pcustID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100003,'message'=>'会员信息不存在'];
        }

        $balance = 0.00;

        //查询账户可用余额
        $cust_account = CustAccount::select('useableAccount')->where(['pcustID'=>$customer['pcustID'],'subjectId'=>2])->first();
        if ( $cust_account ) {
            $balance = app_to_decimal( $cust_account['useableAccount'] );
        }

        return ['code'=>200,'message'=>'ok','data'=>['balance'=>$balance]];
    }


    /**
     * 会员账户增加积分
     * @param $args_array
     * @return array
     */
    public function pointsAdd( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        //积分增加值
        if ( !isset( $args_array['points'] ) || empty( $args_array['points'] ) ) {
            return ['code'=>100002,'message'=>'参数points不能为空'];
        }
        if ( $args_array['points'] < 0 ) {
            return ['code'=>100003,'message'=>'参数points值不能小于0'];
        }

        //查询会员信息
        $customer = Customer::select('pcustID','custID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100004,'message'=>'会员信息不存在'];
        }

        $pcustID = $customer['pcustID']; //会员号
        $custID = $customer['custID']; //会员名

        try {

            //开启事务
            DB::beginTransaction();

            //查询会员账户可用积分
            $cust_account = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>3])->first();

            if ( !$cust_account ) {

                $cust_account_obj = new CustAccount;
                $cust_account_obj->uuid = makeUuid();
                $cust_account_obj->timeStamp = Carbon::now();
                $cust_account_obj->createTime = Carbon::now();
                $cust_account_obj->creator = 'api';
                $cust_account_obj->pcustID = $pcustID; //会员号
                $cust_account_obj->custID = $custID;  //会员名
                $cust_account_obj->subjectId = 3;
                $cust_account_obj->subjectName = '积分';  //账户类型
                $cust_account_obj->lockAccount = 0;  //冻结积分
                $cust_account_obj->useableAccount = $args_array['points'];  //可用积分
                $cust_account_obj->save();
            } else {

                $account_rows = CustAccount::where(['pcustID'=>$pcustID,'subjectId'=>3])->increment('useableAccount',$args_array['points']);
                if ( $account_rows <= 0 ) {
                    return ['code'=>100005,'message'=>'积分增加失败'];
                }
            }

            //保存变更记录
            $log_data = [
                'pcustID' => $pcustID, //会员号
                'custID' => $custID, //会员名
                'subjectId' => 3,
                'subjectName' => '积分',  //账户类型
                'useableAccount' => isset( $cust_account['useableAccount'] ) ? app_to_int($cust_account['useableAccount']) : 0,  //可用积分
                'changeAccount' => $args_array['points'], //变更积分
                'changeType' => 1,  //变更类型 1.增加 2.扣减
                'actionType' => 4, //业务动作类型 4: 充值 5: 消费
                'remark' => !empty( $args_array['remark'] ) ? $args_array['remark'] :''  //备注
            ];

            self::custAccountLog( $log_data );

            //查询会员账户变更后可用积分
            $points_data = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>3])->first();

            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();

            return ['code'=>100006,'message'=>'积分增加失败'];
        }

        return ['code'=>200,'message'=>'ok','data'=>['points'=>app_to_int($points_data['useableAccount'])]];
    }


    /**
     * 会员账户扣减积分
     * @param $args_array
     * @return array
     */
    public function pointsReduction( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        //积分扣减值
        if ( !isset( $args_array['points'] ) || empty( $args_array['points'] ) ) {
            return ['code'=>100002,'message'=>'参数points不能为空'];
        }
        if ( $args_array['points'] < 0 ) {
            return ['code'=>100003,'message'=>'参数points值不能小于0'];
        }

        //查询会员信息
        $customer = Customer::select('pcustID','custID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100004,'message'=>'会员信息不存在'];
        }

        $pcustID = $customer['pcustID']; //会员号
        $custID = $customer['custID']; //会员名

        try {

            //开启事务
            DB::beginTransaction();

            //查询会员账户可用积分
            $cust_account = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>3])->first();

            if ( $cust_account['useableAccount'] < $args_array['points'] ) {
                return ['code'=>100005,'message'=>'积分不足，剩余积分：'.$cust_account['useableAccount']];
            }

            $cust_account_rows = CustAccount::where([
                ['pcustID','=',$pcustID],
                ['subjectId','=',3],
                ['useableAccount','>=',$args_array['points']]
            ])->decrement('useableAccount',$args_array['points']);

            if ( $cust_account_rows <= 0 ) {
                return ['code'=>100006,'message'=>'积分扣减失败'];
            }

            //保存变更记录
            $log_data = [
                'pcustID' => $pcustID, //会员号
                'custID' => $custID, //会员名
                'subjectId' => 3,
                'subjectName' => '积分', //账户类型
                'useableAccount' => isset( $cust_account['useableAccount'] ) ? app_to_int($cust_account['useableAccount']) : 0, //可用积分
                'changeAccount' => $args_array['points'], //变更积分
                'changeType' => 2, //变更类型 1.增加 2.扣减
                'actionType' => 5, //业务动作类型 4: 充值 5: 消费
                'remark' => !empty( $args_array['remark'] ) ? $args_array['remark'] :'' //备注
            ];

            self::custAccountLog( $log_data );

            //查询会员账户变更后可用积分
            $points_data = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>3])->first();

            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();

            return ['code'=>100007,'message'=>'积分扣减失败'];
        }

        return ['code'=>200,'message'=>'ok','data'=>['points'=>app_to_int($points_data['useableAccount'])]];
    }


    /**
     * 会员账户余额充值
     * @param $args_array
     * @return array
     */
    public function recharge( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        //充值金额
        if ( !isset( $args_array['amount'] ) || empty( $args_array['amount'] ) ) {
            return ['code'=>100002,'message'=>'参数amount不能为空'];
        }
        if ( $args_array['amount'] < 0 ) {
            return ['code'=>100003,'message'=>'参数amount值不能小于0'];
        }

        //查询会员信息
        $customer = Customer::select('pcustID','custID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100004,'message'=>'会员信息不存在'];
        }

        $pcustID = $customer['pcustID']; //会员号
        $custID = $customer['custID']; //会员名

        try {

            //开启事务
            DB::beginTransaction();

            //查询会员账户可用余额
            $cust_account = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>2])->first();

            if ( !$cust_account ) {

                $cust_account_obj = new CustAccount;
                $cust_account_obj->uuid = makeUuid();
                $cust_account_obj->timeStamp = Carbon::now();
                $cust_account_obj->createTime = Carbon::now();
                $cust_account_obj->creator = 'api';
                $cust_account_obj->pcustID = $pcustID; //会员号
                $cust_account_obj->custID = $custID; //会员名
                $cust_account_obj->subjectId = 2;
                $cust_account_obj->subjectName = '余额';
                $cust_account_obj->lockAccount = 0;  //冻结余额
                $cust_account_obj->useableAccount = $args_array['amount']; //可用余额
                $cust_account_obj->save();
            } else {

                $account_rows = CustAccount::where(['pcustID'=>$pcustID,'subjectId'=>2])->increment('useableAccount',$args_array['amount']);
                if ( $account_rows <= 0 ) {
                    return ['code'=>100005,'message'=>'余额充值失败'];
                }
            }

            //保存变更记录
            $log_data = [
                'pcustID' => $pcustID, //会员号
                'custID' => $custID, //会员名
                'subjectId' => 2,
                'subjectName' => '余额', //账户类型
                'useableAccount' => isset( $cust_account['useableAccount'] ) ? app_to_decimal( $cust_account['useableAccount'] ) : 0.00, //可用余额
                'changeAccount' => $args_array['amount'], //变更余额
                'changeType' => 1, //变更类型 1.增加 2.扣减
                'actionType' => 4, //业务动作类型 4: 充值 5: 消费
                'remark' => !empty( $args_array['remark'] ) ? $args_array['remark'] :'' //备注
            ];

            self::custAccountLog( $log_data );

            //查询会员账户变更后可用余额
            $balance_data = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>2])->first();

            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();

            return ['code'=>100006,'message'=>'余额充值失败'];
        }

        return ['code'=>200,'message'=>'ok','data'=>['balance'=>app_to_decimal( $balance_data['useableAccount'] )]];
    }


    /**
     * 会员账户余额消费
     * @param $args_array
     * @return array
     */
    public function consumption( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        //消费金额
        if ( !isset( $args_array['amount'] ) || empty( $args_array['amount'] ) ) {
            return ['code'=>100002,'message'=>'参数amount不能为空'];
        }
        if ( $args_array['amount'] < 0 ) {
            return ['code'=>100003,'message'=>'参数amount值不能小于0'];
        }

        //查询会员信息
        $customer = Customer::select('pcustID','custID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100004,'message'=>'会员信息不存在'];
        }

        $pcustID = $customer['pcustID']; //会员号
        $custID = $customer['custID']; //会员名

        try {

            //开启事务
            DB::beginTransaction();

            //查询会员账户可用余额
            $cust_account = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>2])->first();

            if ( $cust_account['useableAccount'] < $args_array['amount'] ) {
                return ['code'=>100005,'message'=>'余额不足，剩余余额：'.$cust_account['useableAccount']];
            }

            $cust_account_rows = CustAccount::where([
                ['pcustID','=',$pcustID],
                ['subjectId','=',2],
                ['useableAccount','>=',$args_array['amount']]
            ])->decrement('useableAccount',$args_array['amount']);

            if ( $cust_account_rows <= 0 ) {
                return ['code'=>100006,'message'=>'余额扣减失败'];
            }

            //保存变更记录
            $log_data = [
                'pcustID' => $pcustID, //会员号
                'custID' => $custID, //会员名
                'subjectId' => 2,
                'subjectName' => '余额', //账户类型
                'useableAccount' => isset( $cust_account['useableAccount'] ) ? app_to_decimal( $cust_account['useableAccount'] ) : 0.00, //可用余额
                'changeAccount' => $args_array['amount'], //变更余额
                'changeType' => 2, //变更类型 1.增加 2.扣减
                'actionType' => 5, //业务动作类型 4: 充值 5: 消费
                'remark' => !empty( $args_array['remark'] ) ? $args_array['remark'] :'' //备注
            ];

            self::custAccountLog( $log_data );

            //查询会员账户变更后可用余额
            $balance_data = CustAccount::select('useableAccount')->where(['pcustID'=>$pcustID,'subjectId'=>2])->first();

            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();

            return ['code'=>100007,'message'=>'余额扣减失败'];
        }

        return ['code'=>200,'message'=>'ok','data'=>['balance'=>app_to_decimal( $balance_data['useableAccount'] )]];
    }


    /**
     * 会员账户积分记录接口
     * @param $args_array
     * @return array
     */
    public function pointsLogs( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        if ( !ebsig_is_int( $args_array['limit'] )) { //每页显示条数,不传默认为10
            $args_array['limit'] = 10;
        }

        if (!ebsig_is_int( $args_array['page'] )) { //页码,不传默认为1
            $args_array['page'] = 1;
        }

        //查询会员信息
        $customer = Customer::select('pcustID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100003,'message'=>'会员信息不存在'];
        }

        //查询会员变更日志
        $cust_account_log = CustAccountLog::select( 'changeAccount','useableAccount','changeType','remark','createTime' )
            ->where(['pcustID'=>$customer['pcustID'],'subjectId'=>3])
            ->paginate( $args_array['limit'] )
            ->toArray();

        //返回数组
        $return_array = [
            'total' => $cust_account_log['total'],
            'list' => []
        ];

        if ( !empty( $cust_account_log['data'] ) ) {

            foreach ($cust_account_log['data'] as $k => $item) {

                $return_array['list'][$k] = [
                    'points' => app_to_int($item['useableAccount']),  //变更前可用积分
                    'create_time' => app_to_string($item['createTime']),
                    'change_account' => app_to_int($item['changeAccount']), //变更额
                    'change_type' => app_to_int($item['changeType']), //变更类型 1.增加 2.扣减
                    'remark' => app_to_string($item['remark'])
                ];
            }
        }

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array];

    }


    /**
     * 会员账户余额记录接口
     * @param $args_array
     * @return array
     */
    public function accountLogs( $args_array )
    {

        //会员卡号
        if ( !isset( $args_array['card_no'] ) || empty( $args_array['card_no'] ) ) {
            return ['code'=>100001,'message'=>'参数card_no不能为空'];
        }

        if ( !ebsig_is_int( $args_array['limit'] )) { //每页显示条数,不传默认为10
            $args_array['limit'] = 10;
        }

        if (!ebsig_is_int( $args_array['page'] )) { //页码,不传默认为1
            $args_array['page'] = 1;
        }

        //查询会员信息
        $customer = Customer::select('pcustID')->where(['cardNo'=>$args_array['card_no']])->first();
        if ( !$customer ) {
            return ['code'=>100003,'message'=>'会员信息不存在'];
        }

        //查询会员变更日志
        $cust_account_log = CustAccountLog::select( 'changeAccount','useableAccount','changeType','remark','createTime' )
            ->where(['pcustID'=>$customer['pcustID'],'subjectId'=>2])
            ->paginate( $args_array['limit'] )
            ->toArray();

        //返回数组
        $return_array = [
            'total' => $cust_account_log['total'],
            'list' => []
        ];

        if ( !empty( $cust_account_log['data'] ) ) {

            foreach ($cust_account_log['data'] as $k => $item) {

                $return_array['list'][$k] = [
                    'balance' => app_to_decimal($item['useableAccount']), //变更前可用余额
                    'create_time' => app_to_string($item['createTime']),
                    'change_account' => app_to_decimal($item['changeAccount']), //变更额
                    'change_type' => app_to_int($item['changeType']), //变更类型 1.增加 2.扣减
                    'remark' => app_to_string($item['remark'])
                ];
            }
        }

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array];

    }


    /**
     * 保存会员账户余额、积分日志
     * @param $args_data
     * @return array
     */
    public function custAccountLog( $args_data )
    {

        $cust_account_log = new CustAccountLog;
        $cust_account_log->uuid = makeUuid();
        $cust_account_log->timeStamp = Carbon::now();
        $cust_account_log->creator = 'api';
        $cust_account_log->createTime = Carbon::now();
        $cust_account_log->operator = 'api';
        $cust_account_log->pcustID = $args_data['pcustID']; //会员号
        $cust_account_log->custID = $args_data['custID']; //会员名
        $cust_account_log->seqno = generate_seqno('seqno_cust_account_log','',true); //交易流水号
        $cust_account_log->subjectId = $args_data['subjectId'];
        $cust_account_log->subjectName = $args_data['subjectName']; //账户类型 2.余额 3.积分
        $cust_account_log->changeAccount = $args_data['changeAccount']; //变更金额
        $cust_account_log->useableAccount = $args_data['useableAccount']; //可用金额(变更前)
        $cust_account_log->changeLockAccount = 0; //变更金额(冻结金额)
        $cust_account_log->lockAccount = 0; //冻结金额(变更前)
        $cust_account_log->source = !empty( $args_data['remark'] ) ? $args_data['remark'] : ''; //来源
        $cust_account_log->changeType = $args_data['changeType']; //变更类型 1.增加 2.扣减
        $cust_account_log->actionType = $args_data['actionType']; //业务动作类型 4: 充值 5: 消费
        $cust_account_log->remark = !empty( $args_data['remark'] ) ? $args_data['remark'] : ''; //备注
        $cust_account_log->save();

    }


    /**
     * 根据手机号查询会员资料
     * @param $args_data
     * @return array
     */
    public function customerQuery( $args_data )
    {

        return [
            'code' => 200,
            'message' =>'ok',
            'data'=>[
                'offline_pcustID' => '',
                'cardNo' => $args_data['mobile'],
                'mobile' => $args_data['mobile'],
                'custname' => ''
            ]
        ];

    }


    /**
     * 会员资料编辑
     * @param $args_data
     * @return array
     */
    public function customerEdit( $args_data )
    {

        return ['code' => 200, 'message' => 'ok'];

    }


    /**
     * 会员开卡接口
     * @param $args_data
     * @return array
     */
    public function openCard( $args_data )
    {
        return [
            'code' => 200,
            'message' => 'ok',
            'data' => [
                'cardNo' => $args_data['mobile'],
                'periodOfValidity' => '',
                'offline_pcustID' => ''
            ]
        ];
    }


    /**
     * 会员绑卡接口
     * @param $args_data
     * @return array
     */
    public function bindCard( $args_data )
    {
        return [
            'code' => 200,
            'message' => 'ok',
            'data' => [
                'cardNo'=>$args_data['mobile']
            ]
        ];
    }

}